const url = getApp().globalData.API_URL;
const CryptoJS = require('crypto-js');
    Component({
      data: {
        text:'',
        httpUrl:"https://spark-api.xf-yun.com/v3.5/chat",
        modelDomain:'',
        APPID:'acec8a44',
        APISecret:'YTFiM2E4ZTMwZWVmMjM1NThkNTAyMzA5',
        APIKey:'671e37fce938f257160bba12792460cf',
        sparkResult:'',
        historyTextList:[],
        messages:[], // 存储消息
        inputValue:'', // 用户输入的消息内容
        bottomViewId:'',
        recording:false,
        path:'',
        showInput:true,
        message:"按住说话",
        isunabled:false,
        categoryList: [
          {
            "name": "餐饮",
            "iconStyleName": "icon-canyin",
            "color": "#02c39a"
          },
          {
            "name": "交通",
            "iconStyleName": "icon-jiaotong",
            "color": "#02c39a"
          },
          {
            "name": "住房",
            "iconStyleName": "icon-zhufang",
            "color": "#02c39a"
          },
          {
            "name": "家庭",
            "iconStyleName": "icon-080jiating",
            "color": "#02c39a"
          },
          {
            "name": "宠物",
            "iconStyleName": "icon-chongwu",
            "color": "#02c39a"
          },
          {
            "name": "购物",
            "iconStyleName": "icon-gouwu",
            "color": "#02c39a"
          },
          {
            "name": "充值",
            "iconStyleName": "icon-chongzhi",
            "color": "#02c39a"
          },
          {
            "name": "水电",
            "iconStyleName": "icon-shuidian",
            "color": "#02c39a"
          },
          {
            "name": "医疗",
            "iconStyleName": "icon-yiliao",
            "color": "#02c39a"
          },
          {
            "name": "烟酒",
            "iconStyleName": "icon-yanjiu",
            "color": "#02c39a"
          },
          {
            "name": "旅游",
            "iconStyleName": "icon-lvyou",
            "color": "#02c39a"
          },
          {
            "name": "借出",
            "iconStyleName": "icon-jiechu",
            "color": "#02c39a"
          },
          {
            "name": "其他",
            "iconStyleName": "icon-qita",
            "color": "#02c39a"
          },
        ],
        categoryList2: [{
          "name": "工资",
          "iconStyleName": "icon-gongzi",
          "color": "#02c39a"
        },
        {
          "name": "兼职",
          "iconStyleName": "icon-jianzhi",
          "color": "#02c39a"
        },
        {
          "name": "理财",
          "iconStyleName": "icon-licai",
          "color": "#02c39a"
        },
        {
          "name": "礼金",
          "iconStyleName": "icon-lijin",
          "color": "#02c39a"
        },
        {
          "name": "其它",
          "iconStyleName": "icon-qita",
          "color": "#02c39a"
        },
        ],
        selectList:[],
        order:'',
        in:["工资","兼职","理财","礼金"],
        out:["餐饮","交通","住房","家庭","宠物","购物","充值","水电","医疗","烟酒","旅游","借出"]
      },
      pageLifetimes:{
        show(){
          this.setData({
            messages:[],
            order:''
          })
        }
      },
      methods: {
        Print:function (str) {
          this.setData({
            historyTextList: [...this.data.historyTextList,{
              type: 'received',
              content: str
            }],
            inputValue: '',
            sparkResult: '',
            text:'',
            message:"按住说话",
            isunabled:false
          });
          this.scrollToBottom(this.data.historyTextList.length - 1)
        },
        isJsonString :function isJsonString(str) {
          try {
              JSON.parse(str);
              return true;
          } catch (e) {
              if (e instanceof SyntaxError) {
                  return false;
              }
          }
      },
        changeMode:function changeMode(){
          var showInput = this.data.showInput;
          showInput = !showInput;
          this.setData({
            showInput:showInput
          })
        },
        startRecording: function(e) {
          if(this.data.isunabled){
            return
          }
          const recorderManager = wx.getRecorderManager();
          if (!this.data.recording) {
            this.setData({
              recording: true,
              message:"请说话"
            });
            recorderManager.start({
              duration: 10000,
              sampleRate: 44100,
              numberOfChannels: 1,
              encodeBitRate: 192000,
              format: 'mp3',
              frameSize: 50
            }); 
            recorderManager.onStart(function () {
              console.log('start');
            });
            recorderManager.onError((res)=>{
              console.log('错误'+res);
            })
          }
        },
        //停止录音
        stopRecording: function(e) {
          if(this.data.isunabled){
            return
          }
          let _this = this;
          const recorderManager = wx.getRecorderManager();
          if (this.data.recording) {
            this.setData({
              recording: false,
              message:"按住说话"
            });
            recorderManager.stop()
            recorderManager.onStop((res)=>{
              if(res.duration<1000){
                wx.showToast({
                  title: '录音时间过短，请重新录音',
                  icon: 'none',
                  duration: 2000
                });
              }else{
                //res.tempFilePath是播放录音的路径
                _this.setData({
                  path:res.tempFilePath,
                  text: '内容正在生成，请稍后...',
                  message:"内容正在生成，请稍后...",
                  isunabled:true,
                })
                console.log(this.data.path);
                //这里可以写语音转文字的方法
                _this.audioToText();
              }
            });
          }
        },
        audioToText: function() {
          let _this = this
          // 使用微信小程序的wx.request发起请求
          wx.uploadFile({
            url: 'https://apikeyplus.com/v1/audio/transcriptions', // API地址
            filePath: _this.data.path, // 音频文件的临时路径
            name: 'file', // 表单中文件对应的key值
            formData: {
              'model': 'whisper-1',
              'language': 'zh',
              'response_format': 'json',
            },
            header: {
              'Authorization': 'Bearer sk-ZLIjsZ2GKFpUnWNP7eB8Db92817f49CeA48574E35a5c0e3a', // 你的令牌
              'content-type': 'multipart/form-data', // 因为是文件上传，所以需要设置为multipart/form-data
            },
            success(res) {
              let json = JSON.parse(res.data)
              console.log(json);
              if(!('text' in json)){
                wx.showToast({
                  title: '服务器忙，重启试试',
                  icon: 'none',
                  duration: 2000
                });
                _this.setData({
                    text:'',
                    message:"按住说话",
                    isunabled:false
                })
                return
              }
              _this.setData({
                text:json.text,
                message:"内容正在生成，请稍后...",
                isunabled:true
              })
              _this.sendToSpark()
            },
            fail(err) {
              console.error('上传失败', err);
              wx.showToast({
                title: '服务器忙，重启试试',
                icon: 'none',
                duration: 2000
              });
              // 处理上传失败的情况
              _this.setData({
                text:'',
                message:"按住说话",
                isunabled:false
              })
            }
          })
        },
        sendToSpark: async function () {
          let _this = this
          if(this.data.text.trim() == ''){
            _this.setData({
              text:'',
              message:"按住说话",
              isunabled:false
            })
            return
          }
          try {
            _this.setData({
              inputValue: _this.data.text.trim()
            });
            if(_this.data.order == '' || !isNaN(_this.data.order)){
              _this.setData({
                messages: [..._this.data.messages, {
                  type: 'sent',
                  content: _this.data.inputValue
                }],
                historyTextList:[..._this.data.historyTextList,{
                  type: 'sent',
                  content: _this.data.inputValue
                }],
                text: '内容正在生成，请稍后...',
                message:"内容正在生成，请稍后...",
                isunabled:true,
              })
              _this.scrollToBottom(_this.data.historyTextList.length - 1);
              wx.request({
                url: `${url}/ChatGptCompletions`,
                data:_this.data.messages,
                method:'POST',
                success: function (res) {
                  console.log(res);
                  if(res.statusCode != 200 || 'error' in res.data){
                    wx.showToast({
                      title: '服务器忙，重启试试',
                      icon: 'none',
                      duration: 2000
                    });
                    _this.setData({
                      inputValue: '',
                      sparkResult: '',
                      text:'',
                      message:"按住说话",
                      isunabled:false
                    })
                    return;
                  }
                  let str = res.data.choices[0].message.content
                  console.log(str);
                  if(_this.isJsonString(str)){
                    let dataBuf = JSON.parse(str);
                    console.log(dataBuf);
                    _this.setData({
                      messages:[]
                    })
                    if(_this.data.order!=''){
                      let index = _this.data.order
                      let data = _this.data.selectList[index-1]
                      if(dataBuf.category == ''){
                        dataBuf.category = data.name
                      }
                      if(dataBuf.comment == ''){
                        dataBuf.comment = data.info
                      }
                      if(dataBuf.value == ''){
                        dataBuf.value = data.caloricSum
                      }else{
                        if((_this.data.in.indexOf(dataBuf.category)!=-1&&dataBuf.value<0)||(_this.data.out.indexOf(dataBuf.category)!=-1&&dataBuf.value>0)){
                          dataBuf.value = -dataBuf.value
                        }
                      }
                      wx.request({
                        url: `${url}/sys-detail/del/${data.did}`,
                        method:'DELETE',
                        success:function (res) {
                          _this.setData({
                            selectList:[],
                            order:''
                          })
                        },
                        fail:function (e) {
                          _this.setData({
                            selectList:[],
                            order:''
                          })
                        }
                      })
                      _this.addGoods(dataBuf);
                      return;
                    }
                    if(dataBuf.intent == '增'){
                      _this.addGoods(dataBuf)
                    }else{
                      if((_this.data.in.indexOf(dataBuf.category)!=-1&&dataBuf.value<0)||(_this.data.out.indexOf(dataBuf.category)!=-1&&dataBuf.value>0)){
                        dataBuf.value = -dataBuf.value
                      }
                      console.log(dataBuf);
                      _this.selike(dataBuf)
                    }
                  }else{
                    _this.setData({
                      messages: [..._this.data.messages,{
                        type: 'received',
                        content: str
                      }],
                      historyTextList: [..._this.data.historyTextList,{
                        type: 'received',
                        content: str
                      }],
                      inputValue: '',
                      sparkResult: '',
                      text:'',
                      message:"按住说话",
                      isunabled:false
                    })
                    _this.scrollToBottom(_this.data.historyTextList.length - 1)
                  }
                },
                fail: function (e) {
                  wx.showToast({
                    title: '服务器忙，重启试试',
                    icon: 'none',
                    duration: 2000
                  });
                  _this.setData({
                    inputValue: '',
                    sparkResult: '',
                    text:'',
                    message:"按住说话",
                    isunabled:false
                  })
                }
              })
            }else if(_this.data.order == '全删'){
              if(_this.data.inputValue == '是'){
                _this.setData({
                  historyTextList:[..._this.data.historyTextList,{
                    type: 'sent',
                    content: _this.data.inputValue
                  }],
                  text: '内容正在生成，请稍后...',
                  message:"内容正在生成，请稍后...",
                  isunabled:true,
                })
                _this.scrollToBottom(_this.data.historyTextList.length - 1);
                _this.deleteAll()
              }else if(_this.data.inputValue == '否'){
                _this.setData({
                  historyTextList:[..._this.data.historyTextList,{
                    type: 'sent',
                    content: _this.data.inputValue
                  }],
                  text: '内容正在生成，请稍后...',
                  message:"内容正在生成，请稍后...",
                  isunabled:true,
                })
                _this.scrollToBottom(_this.data.historyTextList.length - 1);
                _this.setData({
                  order:'部分删'
                })
                _this.Print("进入部分删\n输入要删除部分的序号(必须是数字且使用空格或,分隔/或者填否)")
              }else {
                _this.setData({
                  historyTextList:[..._this.data.historyTextList,{
                    type: 'sent',
                    content: _this.data.inputValue
                  }],
                  text: '内容正在生成，请稍后...',
                  message:"内容正在生成，请稍后...",
                  isunabled:true,
                })
                _this.scrollToBottom(_this.data.historyTextList.length - 1);
                _this.Print("请按要求输入")
              }
            }else if(_this.data.order == '部分删'){
              let _this = this
              _this.setData({
                historyTextList:[..._this.data.historyTextList,{
                  type: 'sent',
                  content: _this.data.inputValue
                }],
                text: '内容正在生成，请稍后...',
                message:"内容正在生成，请稍后...",
                isunabled:true,
              })
              _this.scrollToBottom(_this.data.historyTextList.length - 1);
              let index = _this.data.inputValue.split(/[,， ]/)
              _this.deletePart(index)
            }else if(_this.data.order == '选改'){
              let index = _this.data.inputValue
              _this.setData({
                historyTextList:[..._this.data.historyTextList,{
                  type: 'sent',
                  content: _this.data.inputValue
                }],
                text: '内容正在生成，请稍后...',
                message:"内容正在生成，请稍后...",
                isunabled:true,
              })
              _this.scrollToBottom(_this.data.historyTextList.length - 1);
              if(isNaN(index) || parseInt(index)<1 || parseInt(index)>_this.data.selectList.length){
                _this.Print('修改结束');
                _this.setData({
                  selectList:[],
                  order:''
                })
                return
              }
              _this.update(parseInt(index))
            }
          } catch (error) {
            console.error('Error in sendToSpark:', error);
            this.setData({
              inputValue: '',
              sparkResult: '',
              text:'',
              message:"按住说话",
              isunabled:false
            })
          }
        },
        addGoods:function (data) {
          if(data.category==''||data.value==''){
            let say = "请问"
            let da = "增 时间"+data.startTime
            console.log(da);
            if(data.category==''){
              say += "账单的类目是什么呢？"
            }else{
              da +=" 类目"+data.category
            }
            if(data.value==''){
              say += "金额是多少呢？"
            }else{
              da +=" 金额"+data.value
            }
            this.Print(say);
            this.setData({
              messages:[...this.data.messages,{type: 'received',content: da},{type: 'received',content: say}]
            })
            return
          }
          let _this = this
          let time = new Date(data.startTime);
          let year = new Date().getFullYear()
          let month = new Date().getMonth()+1
          let day = new Date().getDate()
          let t =year + '-' + month + '-' + day
          t = parseInt(new Date(t).getTime());
          let date2 = parseInt(new Date().getTime())
          let change = date2 - t 
          let date = parseInt(time.getTime()) + change - 8*60*60*1000 ;
          console.log(date);
          let goodsInfo = {
            uid:wx.getStorageSync('token'),
            name:data.category,
            kind:data.value<0?0:1,
            info:data.comment,
            date:date,
            caloricSum:data.value*100
          }
          this.data.categoryList.forEach(category=>{
            if(data.category == category.name){
              goodsInfo.specification = category.iconStyleName;
            }
          })
          this.data.categoryList2.forEach(category=>{
            if(data.category == category.name){
              goodsInfo.specification = category.iconStyleName;
            }
          })
          return wx.request({
            url: `${url}/sys-detail/add?caloricSum=${goodsInfo.caloricSum}
            &date=${goodsInfo.date}
            &info=${goodsInfo.info}
            &kind=${goodsInfo.kind}
            &name=${goodsInfo.name}
            &pid=0
            &quantity=0
            &specification=${goodsInfo.specification}
            &uid=${goodsInfo.uid}`,
            method: 'POST',
            success: function (res) {
              console.log('数据发送成功', res);
              console.log('数据发送成功', goodsInfo);
              console.log(res.statusCode);
              if (res.statusCode == 200) {
                _this.Print("记录成功")
              } 
              else {
                _this.Print("记录失败")
              }
            },
            fail: function (err) {
              console.error('数据发送失败', err);
              _this.Print("记录失败")
            },
          });
        },
        deleteAll:function () {
          let _this = this
          let requests = []
          this.data.selectList.forEach(data=>{
            console.log(data);
            requests.push(new Promise((resolve,reject)=>{
              wx.request({
                url: `${url}/sys-detail/del/${data.did}`,
                method:'DELETE',
                success:function (res) {
                  resolve(res)
                },
                fail:function (e) {
                  reject(e)
                }
              })
            }))
          })
          Promise.all(requests).then(response=>{
            _this.Print("删除成功")
            _this.setData({
              selectList:[],
              order:''
            })
          }).catch(e=>{
            console.log(e);
            _this.Print("删除失败或部分失败")
            _this.setData({
              selectList:[],
              order:''
            })
          })
        },
        deletePart:function (index) {
          let _this = this
          let requests = []
          let list = _this.data.selectList
          index.forEach(i=>{
            if(isNaN(i)||parseInt(i)<1||parseInt(i)>list.length){
              return
            }
            requests.push(new Promise((resolve,reject)=>{
              wx.request({
                url: `${url}/sys-detail/del/${list[parseInt(i-1)].did}`,
                method:'DELETE',
                success:function (res) {
                  resolve(res)
                },
                fail:function (e) {
                  reject(e)
                }
              })
            }))
          })
          Promise.all(requests).then(response=>{
            _this.Print("删除成功")
            _this.setData({
              selectList:[],
              order:''
            })
          }).catch(e=>{
            console.log(e);
            _this.Print("删除失败或部分失败")
            _this.setData({
              selectList:[],
              order:''
            })
          })
        },
        update:function (index) {
          this.setData({
            order:index,
            messages:[{type: 'sent',content:"改"}]
          })
          this.Print("请提供更改的详细信息")
        },
        selike:function (data) {
          let _this = this
          this.setData({
            selectList:[]
          })
          let uid = wx.getStorageSync("token")
          console.log(uid);
          let startTime = new Date(data.startTime)
          let endTime = new Date(data.endTime)
          let time = startTime;
          let requests=[]
          while(time<=endTime){
            let year = time.getFullYear()
            let month = (time.getMonth()+1)<10?'0'+(time.getMonth()+1):(time.getMonth()+1)
            let day = time.getDate()
            let date = '' + year + month + day 
            console.log(date);
            requests.push(new Promise((resolve,reject)=>{
              wx.request({
                url: `${url}/sys-detail/selike/${uid}/${data.category==''?'null':data.category}/${data.value==''?'null':(data.value*100)}/${date}`,
                method:'GET',
                success:function (res) {
                  var datas = res.data;
                  for (var data of datas) {
                    data.caloricSum = parseFloat(data.caloricSum / 100).toFixed(2);
                    var year = data.date.slice(0,4); 
                    var month = data.date.slice(4,6);
                    var day = data.date.slice(6,8);
                    data.date = year+'-'+month+'-'+day;
                    data.name = data.name.trim();
                    data.specification = data.specification.trim();
                    data.info = data.info.trim();
                    _this.setData({
                      selectList:[..._this.data .selectList,data]
                    })
                  }
                  console.log(_this.data.selectList);
                  resolve(res.data)
                },
                fail:function (e) {
                  reject(e)
                }
              })
            }))
            time.setTime(time.getTime()+(24*60*60*1000))
          }
          Promise.all(requests).then(response=>{  
            console.log("所有异步已完成",response);
            console.log(_this.data.selectList);
            if(_this.data.selectList.length == 0){
                _this.Print('查无记录') 
            }else{
              let content = '记录如下：\n'
              let list = _this.data.selectList
              let index = 0
              for(;index<list.length;index++){
                content += `${index+1}、类型：${list[index].name}\n      备注：${list[index].info}\n      日期：${list[index].date}\n      金额：${list[index].caloricSum}\n`
              }
              _this.Print(content) 
              console.log(data);
              if(data.intent == '删'){
                _this.Print("是否全部删除(是/否)");
                _this.setData({
                  order:'全删',
                })
              }else if(data.intent == '改'){
                _this.setData({
                  order:'选改'
                })
                _this.Print("选一个你要修改的序号(数字)/输入非数字以取消")
              }else{
                _this.setData({
                  selectList:[]
                })
              }
            }
          }).catch(error=>{
            console.log(error);
            _this.Print("查询失败")
            _this.setData({
              selectList:[]
            })
          })
        },
        inputchange:function (e) {
          this.setData({
            text:e.detail.value
          })
        },
        scrollToBottom: function(e) {
          console.log("数组长度："+(e+1))
          console.log("bottomViewId："+e)
          this.setData({
            bottomViewId:'msg-' + e
          })
        },
        getWebSocketUrl: function getWebSocketUrl() {
          let _this = this
          console.log(this.data.httpUrl);
          var httpUrlHost = this.data.httpUrl.substring(8, 28);
          var httpUrlPath = this.data.httpUrl.substring(28);
          console.log(httpUrlHost);
          console.log(httpUrlPath);
          switch (httpUrlPath) {
            case "/v1.1/chat":
              _this.data.modelDomain = "general";
              break;
            case "/v2.1/chat":
              _this.data.modelDomain = "generalv2";
              break;
            case "/v3.1/chat":
              _this.data.modelDomain = "generalv3";
              break;
            case "/v3.5/chat":
              _this.data.modelDomain = "generalv3.5";
              break;
          }
          console.log(_this.modelDomain);
          return new Promise(function (resolve, reject) {
          var url = "wss://" + httpUrlHost + httpUrlPath;
          var host = "spark-api.xf-yun.com";
          var apiKeyName = "api_key";
          var date = new Date().toGMTString();
          var algorithm = "hmac-sha256";
          var headers = "host date request-line";
          var signatureOrigin = "host: ".concat(host, "\ndate: ").concat(date, "\nGET ").concat(httpUrlPath, " HTTP/1.1");
          var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, _this.data.APISecret);
          var signature = CryptoJS.enc.Base64.stringify(signatureSha);
          var authorizationOrigin = "".concat(apiKeyName, "=\"").concat(_this.data.APIKey, "\", algorithm=\"").concat(algorithm, "\", headers=\"").concat(headers, "\", signature=\"").concat(signature, "\"");
          
          // 使用crypto-js库中的Base64编码
          var authorization = CryptoJS.enc.Utf8.parse(authorizationOrigin).toString(CryptoJS.enc.Base64);
        
          url = "".concat(url, "?authorization=").concat(encodeURIComponent(authorization), "&date=").concat(encodeURIComponent(date), "&host=").concat(host);
          resolve(url);
        });
        }
      }
    })
    